import React, { useEffect, useState } from "react";
import { Button, Card, Input } from "antd";
import { useAddTask } from "server";
import { useProjectIdUrl } from "./util";

const CreateTaks: React.FC<{ kanbanId: number }> = (props) => {
  const [name, setNmae] = useState("");
  const [inputMode, setInputMode] = useState(false);
  const projectId = useProjectIdUrl();
  const { mutateAsync: addTask } = useAddTask();

  const submit = async () => {
    await addTask({ name, projectId, kanbanId: props.kanbanId });
    setNmae("");
    setInputMode(false);
  };

  const toggle = () => setInputMode((m) => !m);

  useEffect(() => {
    if (!inputMode) setNmae("");
  }, [inputMode]);

  if (!inputMode) {
    return (
      <Button onClick={toggle} type="text">
        +创建任务
      </Button>
    );
  }

  return (
    <Card>
      <Input
        autoFocus
        onBlur={toggle}
        placeholder="需要做些什么"
        onPressEnter={submit}
        value={name}
        onChange={(evt) => setNmae(evt.target.value)}
      />
    </Card>
  );
};

export default CreateTaks;
